package com.healthyeating.manage.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import com.healthyeating.common.utils.DateUtils;
import com.healthyeating.common.utils.SecurityUtils;
import com.healthyeating.manage.domain.Product;
import com.healthyeating.manage.domain.dto.ShopListProductDto;
import com.healthyeating.manage.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.healthyeating.manage.mapper.ShopListMapper;
import com.healthyeating.manage.domain.ShopList;
import com.healthyeating.manage.service.IShopListService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 清单管理Service业务层处理
 *
 * @author 段奇乐
 * @date 2024-11-26
 */
@Service
public class ShopListServiceImpl implements IShopListService {

    @Autowired
    private ShopListMapper shopListMapper;

    @Autowired
    private ProductMapper productsMapper;

    /**
     * 查询清单管理
     *
     * @param listId 清单管理主键
     * @return 清单管理
     */
    @Override
    public ShopListProductDto selectShopListByListId(Long listId) {
        List<Product> productList = productsMapper.selectProductByListId(listId);
        ShopList shopList = shopListMapper.selectShopListByListId(listId);
        ShopListProductDto shopListProductDTO = new ShopListProductDto();
        BeanUtil.copyProperties(shopList, shopListProductDTO);
        shopListProductDTO.setProductList(productList);
        return shopListProductDTO;
    }

    /**
     * 查询清单管理列表
     *
     * @param shopList 清单管理
     * @return 清单管理
     */
    @Override
    public List<ShopList> selectShopListList(ShopList shopList) {
        shopList.setUserId(SecurityUtils.getUserId());
        return shopListMapper.selectShopListList(shopList);
    }

    /**
     * 新增清单管理
     *
     * @param shopListProductDto 清单管理
     * @return 结果
     */
    @Override
    @Transactional
    public int insertShopList(ShopListProductDto shopListProductDto) {
        // 获取创建时间和更新时间
        shopListProductDto.setCreateTime(DateUtils.getNowDate());
        shopListProductDto.setUpdateTime(DateUtils.getNowDate());
        shopListProductDto.setStatus(0);
        shopListProductDto.setUserId(SecurityUtils.getUserId());
        int result = shopListMapper.insertShopList(shopListProductDto);
        // 获取商品列表
        List<Product> productList = shopListProductDto.getProductList();
        if (!productList.isEmpty()) {
            List<Product> list = productList.stream().peek(product -> {
                product.setStatus(0);
                product.setShopListId(shopListProductDto.getListId());
                product.setListName(shopListProductDto.getListName());
                product.setUserId(SecurityUtils.getUserId());
                product.setCreateTime(DateUtils.getNowDate());
            }).collect(Collectors.toList());
            productsMapper.batchInsertProduct(list);
        }
        return result;
    }

    /**
     * 修改清单管理
     *
     * @param shopListProductDto 清单管理
     * @return 结果
     */
    @Override
    @Transactional
    public int updateShopList(ShopListProductDto shopListProductDto) {
        // 获取前端发送的商品列表
        List<Product> productList = shopListProductDto.getProductList();
        // 提取出前端发送的商品列表中有productId的数据和没有productId的数据
        List<Product> addProductList = productList.stream().filter(product -> product.getProductId() == null).collect(Collectors.toList());
        List<Product> updateProductList = productList.stream().filter(product -> product.getProductId() != null).collect(Collectors.toList());
        // 查询清单下的所有商品
        List<Product> products = productsMapper.selectProductByListId(shopListProductDto.getListId());
        if (updateProductList.size() < products.size()) {
            // 比较updateProductList的所有id和products的所有id，从products中提取出updateProductList中没有的id
            List<Long> productIds = products.stream().map(Product::getProductId).collect(Collectors.toList());
            List<Long> deleteProductIds = productIds.stream().filter(productId -> !updateProductList.stream().map(Product::getProductId).collect(Collectors.toList()).contains(productId)).collect(Collectors.toList());
            // 批量删除
            productsMapper.deleteProductByProductIds(deleteProductIds.toArray(new Long[0]));
        }
        if (!addProductList.isEmpty()) {
            // 批量插入新数据
            List<Product> addProducts = addProductList.stream().peek(product -> {
                product.setStatus(0);
                product.setShopListId(shopListProductDto.getListId());
                product.setListName(shopListProductDto.getListName());
                product.setUserId(SecurityUtils.getUserId());
                product.setCreateTime(DateUtils.getNowDate());
            }).collect(Collectors.toList());
            productsMapper.batchInsertProduct(addProducts);
        }
        // 批量修改
        if (!updateProductList.isEmpty()) {
            List<Product> updateProducts = updateProductList.stream().peek(product -> product.setListName(shopListProductDto.getListName())).collect(Collectors.toList());
            productsMapper.batchUpdateProduct(updateProducts);
        }
        return shopListMapper.updateShopList(shopListProductDto);
    }

    /**
     * 批量删除清单管理
     *
     * @param listIds 需要删除的清单管理主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteShopListByListIds(Long[] listIds) {
        // 查看清单下是否有商品，如果有抛出异常
//        for (Long listId : listIds) {
//            List<Product> productList = productsMapper.selectProductByListId(listId);
//            if (!productList.isEmpty()) {
//                throw new ServiceException("该清单下有商品，无法删除");
//            }
//        }
        int result = shopListMapper.deleteShopListByListIds(listIds);
        productsMapper.deleteProductByListIds(listIds);
        return result;
    }

    /**
     * 删除清单管理信息
     *
     * @param listId 清单管理主键
     * @return 结果
     */
    @Override
    public int deleteShopListByListId(Long listId) {
        return shopListMapper.deleteShopListByListId(listId);
    }
}
